const express = require('express')
const path = require('path')
const config = require(path.join(__dirname,"config"))
// 方便返回错误的第三方插件
const createError = require('http-errors')
// 返回漂亮的JS错误提示第三方插件
const Youch = require('youch')
const morgan = require('morgan')
const favicon = require('express-favicon')
const cookieParser = require('cookie-parser')
const bodyParser = require('body-parser')
const session = require('express-session')
// const MySQLStore = require('express-mysql-session')(session)

const app = express()

// 日志中间件，要在所有中间件前面
app.use(morgan('dev'))

// 图标的中间件
app.use(favicon(path.join(__dirname + '/public/assets/favicon.ico')));

// 集成中间件
app.use(express.static(path.join(__dirname,"public")))

app.engine('art', require('express-art-template'))
// 设置默认模版引擎
app.set('view engine','art')
// 设置模版引擎选项
app.set('view options', {
  debug: process.env.NODE_ENV !== 'production'
})

// const sessionStore = new MySQLStore(config.mysql);
 
app.use(session({
    key: 'pyg_session_key',
    secret: 'pyg_session_secret',
    // store: sessionStore,
    resave: false,
    saveUninitialized: false
}))

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(cookieParser())

// 执行自定义中间件
const middleware = require(path.join(__dirname,'middleware'))
app.use(middleware.global)

// 执行路由中间件
const routers = require(path.join(__dirname,"routers"))
app.use(routers)

// 没有匹配到任何组件，则返回404
app.use((req, res, next) => {
  next(createError(404, 'Not Found'))
})

// 统一处理错误
app.use((error, req, res, next) => {
  if (req.app.get('env') === 'development') {
    const youch = new Youch(error, req)

    return youch.toHTML().then(html => {
      res.send(html)
    })
  }

  // 设置模版的数据
  res.locals.status = error.status === 404 ? '404' : 500
  res.render(path.join(__dirname,"./views/error.art"))
})

app.listen(3000, err => console.log('start OK'))
